package com.hyg.module_report.ui.activity;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.Constants;
import com.hyg.module_report.R;
import com.hyg.module_report.adapter.SelfReportAdapter;
import com.hyg.module_report.model.ReportListData;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import okhttp3.FormBody;

/**   我的自检结果列表 页面   */
@Route(path = Constants.PATH_ACTIVITY_MODULE_REPORTS_SELFTEST)
public class SelfTestResultActivity extends BaseActivity {

    protected void onStop(){
        super.onStop();
        if(this.isFinishing()){
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    private RecyclerView RV_Self_Result;
    private SelfReportAdapter reportListAdapter;
    private ArrayList<ReportListData> reportListData = new ArrayList<>();
    private ImageView back,add,iv_zanwubaogao;
    private TextView tv_self_result;
    private RefreshLayout refreshLayout;


    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private SelfTestResultActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (SelfTestResultActivity) reference.get();
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://获取自检结果数据列表
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeReportList", jsondata+"");
                        if (status.equals("200")) {
                            activity.reportListData.clear();
                            if(!Utils.isEmpty(jsondata.getString("data")) && !jsondata.getString("data").equals("null")) {
                                JSONArray datas = new JSONArray(URLDecoder.decode(jsondata.getString("data"), "utf-8"));
                                if (datas.length() != 0) {
                                    for (int i = 0; i < datas.length(); i++) {
                                        JSONObject data = new JSONObject(datas.get(i).toString());
                                        ReportListData item = new ReportListData(
                                                (data.getString("id").equals("null") ? "" : data.getString("id")),
                                                activity.sn.getString("realName",""),
                                                stampToDate(data.getString("createTime").equals("null") ? "" : data.getString("createTime")),
                                                data.getString("answer").equals("null") ? "" : data.getString("answer"));
                                        activity.reportListData.add(item);
                                    }
                                }
                            }
                        } else {
                            activity.ErrorDialog(message);
                        }
                        activity.onRefreshing();

                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_test_result);
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.white),00,null,null,true);

        init();
        GetMyselfListAddr();
    }

    public void init(){
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {if(Utils.isFastClick()){return ;}
                SelfTestResultActivity.this.finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });

        add = (ImageView)findViewById(R.id.add);
//        add.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {if(Utils.isFastClick()){return ;}
//                Intent it = new Intent(ReportListScreen.this,InsertReport.class);
//                startActivity(it);
//                overridePendingTransition(R.anim.fade, R.anim.hold);
//            }
//        });
        iv_zanwubaogao = (ImageView)findViewById(R.id.iv_zanwubaogao);
        tv_self_result = (TextView) findViewById(R.id.tv_self_result);

        refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        refreshLayout.setDragRate(0.5f);//显示下拉高度/手指真实下拉高度=阻尼效果
        refreshLayout.setReboundDuration(300);//回弹动画时长（毫秒）
        refreshLayout.setHeaderHeight(40);//Header标准高度（显示下拉高度>=标准高度 触发刷新）
        refreshLayout.setHeaderMaxDragRate(2);//最大显示下拉高度/Header标准高度
        refreshLayout.setHeaderTriggerRate(1);//触发刷新距离 与 HeaderHeight 的比率1.0.4
        refreshLayout.setFooterTriggerRate(0.5f);//触发加载距离 与 FooterHeight 的比率1.0.4

        refreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能f
        refreshLayout.setEnableLoadMore(false);//是否启用上拉加载功能
        refreshLayout.setEnableOverScrollBounce(true);//是否启用越界回弹
        refreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        refreshLayout.setEnableHeaderTranslationContent(true);//是否下拉Header的时候向下平移列表或者内容
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能
        refreshLayout.setDisableContentWhenRefresh(false);//是否在刷新的时候禁止列表的操作
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                GetMyselfListAddr();
                refreshlayout.finishRefresh(1500/*,false*/);//传入false表示刷新失败
            }
        });

        RV_Self_Result = (RecyclerView)findViewById(R.id.RV_Self_Result);
        reportListAdapter = new SelfReportAdapter(this,reportListData);
        RV_Self_Result.setNestedScrollingEnabled(false);
        RV_Self_Result.setLayoutManager(new GridLayoutManager(this,1));
        RV_Self_Result.setAdapter(reportListAdapter);
        RV_Self_Result.setItemAnimator(new DefaultItemAnimator());
        reportListAdapter.setOnItemClickLitener(new SelfReportAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
//                Intent it = new Intent(SelfTestResultActivity.this,WebViewActivity.class);
//                if(reportListData.size() != 0 && reportListData.size() > position){
//                    it.putExtra("url", reportListData.getposition());
//                    startActivity(it);
//                }else{
////                    new AlertDialog.Builder(SelfTestResultActivity.this)
////                            .setMessage("当前活动无实体内容，敬请期待")
////                            .setPositiveButton("我知道了！", new DialogInterface.OnClickListener() {
////                                public void onClick(DialogInterface dialog, int arg1) {
////                                    if (Utils.isFastClick()) {
////                                        return;
////                                    }
////                                }
////                            }).show();
//                }
            }
            public void onItemLongClick(View view, int position) {

            }
        });

    }
    public void onResume(){
        super.onResume();

    }

    public void onRefreshing(){
        if(reportListData.size() != 0){
            Collections.reverse(reportListData);//倒序排列(反转)
            iv_zanwubaogao.setVisibility(View.GONE);
            tv_self_result.setVisibility(View.GONE);
            if(RV_Self_Result.getScrollState() == 0) {
                reportListAdapter.notifyDataSetChanged();
            }
        }else{
            iv_zanwubaogao.setVisibility(View.VISIBLE);
            tv_self_result.setVisibility(View.VISIBLE);
        }
    }
    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }
    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public void GetMyselfListAddr(){
        if(UINetWork(NetworkUtils.isConnected(this)))//检查网络是否断开的 提示，决定是否访问服务器
        {
            String str_tag = "1";
//            String data = "token=" + sn.getString("token", "");
            FormBody formBody = new FormBody.Builder()
//                    .add("token", sn.getString("token", ""))//设置参数名称和参数值
//                    .add("edition", "0")//设置参数名称和参数值
                    .add("phone", sn.getString("phone",""))//设置参数名称和参数值
                    .add("org", "hyg")//设置参数名称和参数值
                    .build();
            sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getMyselfListAddr);
        }
    }

}
